package andev.schoolhelper.main;

import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.GridLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import andev.aandroidlib.activity.ANetActivity;
import andev.aandroidlib.listener.ATouch;
import andev.schoolhelper.R;
import andev.schoolhelper.apputil.SchoolUtil;
import andev.schoolhelper.course.Course_Card;
import andev.schoolhelper.course.Course_Index;

public class CourseFragment extends Fragment {
    private static int nowWeek = 1, addOnce = -1;
    private static long selectedWeek = 0;
    private LinearLayout root;
    private int d;
    private ArrayList<JSONObject> courseJSONs;
    private GridLayout courseView;
    /* Angus
     * 2015年7月20日 上午9:39:58
     * 初始化CourseFragment的ActionBar，包含一个可被
     */
    private TextView week_dropdown;
    private ImageView actionbar_menu;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //获取屏幕size
        Point size = new Point();
        getActivity().getWindowManager().getDefaultDisplay().getSize(size);
        d = size.x / (1 + 7 * 2) - 1;//margin is 1,so a card is width-2 in real, and d should -1

        root = (LinearLayout) inflater.inflate(R.layout.fragment_course, container, false);

        SharedPreferences nowWeekSharedPreferences = getActivity().getApplicationContext().getSharedPreferences("nowWeek", Context.MODE_PRIVATE);
        nowWeek = nowWeekSharedPreferences.getInt("nowWeek", 1);

        addOnce = nowWeekSharedPreferences.getInt("nowWeek", -1);
        if (addOnce == -1) {
            nowWeekSharedPreferences.edit().putInt("addOnce", 1).commit();
            addOnce = 1;
        }
        if (addOnce == 1) {
            if (getDayOfWeek() == 1) {
                nowWeek++;
                nowWeekSharedPreferences.edit().putInt("nowWeek", nowWeek).commit();
                addOnce = 0;
            } else {
                addOnce = 1;
                nowWeekSharedPreferences.edit().putInt("addOnce", 1).commit();
            }
        }

        InitActionBar();
        InitBaseView();
        GetLocalCourseDataView();
        return root;
    }

    private void InitActionBar() {
        MainActivity mainActivity = (MainActivity) this.getActivity();

        week_dropdown = mainActivity.getActionbar_middle_tv();
        week_dropdown.setGravity(Gravity.CENTER);

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        week_dropdown.setLayoutParams(layoutParams);

        week_dropdown.setText("第" + nowWeek + "周");
        week_dropdown.setTextColor(Color.WHITE);

        //week_dropdown.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_course_week_dropdown, 0);
        Drawable week_dropdown_drawable = getResources().getDrawable(R.mipmap.ic_course_week_dropdown);
        week_dropdown_drawable.setBounds(0, 0, 8, 8);
        week_dropdown.setCompoundDrawables(null, null, week_dropdown_drawable, null);
        week_dropdown.setCompoundDrawablePadding(8);

        week_dropdown.setClickable(true);
        week_dropdown.setOnTouchListener(new ATouch() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    showCourseWeekDropdown();
                }
                return super.onTouch(v, event);
            }
        });

        actionbar_menu = mainActivity.getActionbar_menu();
        actionbar_menu.setOnTouchListener(new ATouch() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    showCourseMenuDropdown();
                }
                return super.onTouch(v, event);
            }
        });

        mainActivity.actionbarLayout.addView(week_dropdown);
    }

    private void InitBaseView() {
        //添加周视图的固定日期栏
        FrameLayout course_week_view = (FrameLayout) root.findViewById(R.id.course_week_view);
        course_week_view.addView(makeWeekIndexView());

        courseView = new GridLayout(getActivity());
        courseView.setOrientation(GridLayout.VERTICAL);
        courseView.setRowCount(14);
        courseView.setColumnCount(8);

        FrameLayout course_scroll = (FrameLayout) root.findViewById(R.id.course_scroll);
        course_scroll.addView(courseView);
    }

    private void beforeGetData() {
        courseView.removeAllViews();

        for (int i = 0; i < 14; i++) {
            addCourse_Index(courseView, d, 2 * d, (i + 1) + "", Color.parseColor("#80ffffff"));
        }
        for (int j = 1; j <= 7; j++) {
            addCourse_Card(courseView, 2 * d, 2 * d, "", 13, j, Color.TRANSPARENT);
        }
        updateTermFromLocal();
    }

    private void updateTermFromLocal() {
        SharedPreferences loginPreferences = getActivity().getApplicationContext().getSharedPreferences("QueryCourseSetting", Context.MODE_PRIVATE);
        String xnd = loginPreferences.getString("xnd", "");
        String xqd = loginPreferences.getString("xqd", "");
        if (!xnd.equals("") && !xqd.equals("")) {
            SchoolUtil.xnd = xnd;
            SchoolUtil.xqd = xqd;
        }
    }

    private void GetLocalCourseDataView() {
        beforeGetData();
        SharedPreferences courseLocalSharedPreferences = getActivity().getApplicationContext().getSharedPreferences("CourseDataLocal", Context.MODE_PRIVATE);
        int xndxqdCourseArraySize = courseLocalSharedPreferences.getInt(SchoolUtil.xnd + SchoolUtil.xqd + "xndxqdCourseArraySize", 0);
        if (xndxqdCourseArraySize == 0) {
            GetNetCourseDataView();
            return;
        }
        ArrayList<JSONObject> fromLocal = new ArrayList<>();
        for (int i = 0; i < xndxqdCourseArraySize; i++) {
            String xndxqdCourseArrayElement = courseLocalSharedPreferences.getString(SchoolUtil.xnd + SchoolUtil.xqd + "xndxqdCourseArrayElement" + i, "");
            try {
                JSONObject jsonObject = new JSONObject(xndxqdCourseArrayElement);
                fromLocal.add(jsonObject);
                //Log.i("----",jsonObject.getInt("day")+":"+jsonObject.getInt("sectionA")+":"+jsonObject.getInt("rowspan")+":"+jsonObject.getString("coursename")+":"+jsonObject.getString("teacher")+":"+jsonObject.getString("classroom"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        CourseFragment.this.courseJSONs = fromLocal;
        makeCourseDataView(courseView);
    }

    private void GetNetCourseDataView() {
        beforeGetData();

        SharedPreferences sharedPreferences = getActivity().getApplicationContext().getSharedPreferences("LoginToSchool", Context.MODE_PRIVATE);
        String username = sharedPreferences.getString("course_username", "");
        String password = sharedPreferences.getString("course_password", "");
        if (username.equals("") || password.equals("")) {
            if (SchoolUtil.course_username.equals("") || SchoolUtil.course_password.equals("")) {
                CourseFragment.this.showCourseLoginDialog();
                return;
            }
        } else {
            SchoolUtil.course_username = username;
            SchoolUtil.course_password = password;
        }


        SchoolUtil schoolUtil = new SchoolUtil((ANetActivity) this.getActivity()) {
            @Override
            public void queryCourseCallback(ArrayList<JSONObject> courseJSONs2) {
                if (courseJSONs2.size() != 0)
                    Toast.makeText(getActivity(), "拉取数据完毕...", Toast.LENGTH_SHORT).show();
                else {
                    Toast.makeText(getActivity(), "暂无课程", Toast.LENGTH_SHORT).show();
                    return;
                }
                CourseFragment.this.courseJSONs = courseJSONs2;
                makeCourseDataView(courseView);

                SharedPreferences courseLocalSharedPreferences = getActivity().getApplicationContext().getSharedPreferences("CourseDataLocal", Context.MODE_PRIVATE);
                Editor editor = courseLocalSharedPreferences.edit();
                int xndxqdCourseArraySize = courseJSONs2.size();
                editor.putInt(SchoolUtil.xnd + SchoolUtil.xqd + "xndxqdCourseArraySize", xndxqdCourseArraySize);
                for (int i = 0; i < xndxqdCourseArraySize; i++) {
                    editor.putString(SchoolUtil.xnd + SchoolUtil.xqd + "xndxqdCourseArrayElement" + i, courseJSONs2.get(i).toString());
                }
                editor.commit();
            }

            @Override
            public void loginToSchoolFailed() {
                Toast.makeText(getActivity(), "登录失败，无法获取课程", Toast.LENGTH_SHORT).show();
                SchoolUtil.course_username = SchoolUtil.course_password = "";
                SharedPreferences loginPreferences = getActivity().getApplicationContext().getSharedPreferences("LoginToSchool", Context.MODE_PRIVATE);
                Editor editor = loginPreferences.edit();
                editor.putString("course_username", SchoolUtil.course_username);
                editor.putString("course_password", SchoolUtil.course_password);
                editor.commit();
            }

            @Override
            public void loginToSchoolSuccess() {
                SharedPreferences courseSettingPreferences = getActivity().getApplicationContext().getSharedPreferences("QueryCourseSetting", Context.MODE_PRIVATE);
                String xnd = courseSettingPreferences.getString("xnd", null);
                String xqd = courseSettingPreferences.getString("xqd", null);
                if (xnd == null || xqd == null) {
                    Toast.makeText(getActivity(), "首次登录成功,请设置学期", Toast.LENGTH_SHORT).show();
                } else
                    Toast.makeText(getActivity(), "教务处访问成功...", Toast.LENGTH_SHORT).show();
                SharedPreferences loginPreferences = getActivity().getApplicationContext().getSharedPreferences("LoginToSchool", Context.MODE_PRIVATE);
                Editor editor = loginPreferences.edit();
                editor.putString("course_username", SchoolUtil.course_username);
                editor.putString("course_password", SchoolUtil.course_password);
                editor.commit();
                WatchCourse();
            }
        };
        schoolUtil.loginToSchool(SchoolUtil.course_username, SchoolUtil.course_password);
    }

    private GridLayout makeCourseDataView(GridLayout courseView) {
        for (JSONObject jsonObject : courseJSONs) {
            String coursename = "", classroom = "", week = "";
            int day = 0, sectionA = 0, rowspan = 0;
            try {
                week = jsonObject.getString("week");
                day = jsonObject.getInt("day");
                sectionA = jsonObject.getInt("sectionA");
                coursename = jsonObject.getString("coursename");
                classroom = jsonObject.getString("classroom");
                rowspan = jsonObject.getInt("rowspan");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            int col = day;
            int row = sectionA - 1;
            int rowSpan = rowspan;
            if (!weekValid(week)) {
                addCourse_Card(courseView, 2 * d, 2 * d * rowSpan, coursename + "\n@" + classroom, row, col, -1);
            } else {
                addCourse_Card(courseView, 2 * d, 2 * d * rowSpan, coursename + "\n@" + classroom, row, col, 1);
            }
        }
        return courseView;
    }

    private boolean weekValid(String week) {
        if (week.contains("undefined")) {
            return true;
        }
        String[] week012 = week.split(",");
        int iWeek012 = Integer.parseInt(week012[1]);

        String[] weekAB = week012[0].split("-");
        int weekA = Integer.parseInt(weekAB[0]);
        int weekB = Integer.parseInt(weekAB[1]);

        int compareWeek = (int) ((selectedWeek != 0) ? selectedWeek : nowWeek);
        if (compareWeek < weekA || compareWeek > weekB) {
            return false;
        }
        if (iWeek012 != 0) {
            if (iWeek012 == 1 && compareWeek % 2 == 0) {
                return false;
            }
            if (iWeek012 == 2 && compareWeek % 2 != 0) {
                return false;
            }
        }
        return true;
    }

    private GridLayout makeWeekIndexView() {
        GridLayout week_view = new GridLayout(getActivity());
        week_view.setColumnCount(8);

        int dayOfWeek = getDayOfWeek();
        int dayOfMonth = getDayOfMonth();
        int month = getMonth();
        for (int i = 0; i < 8; i++) {
            if (i == 0)//Month index
            {
                if (dayOfMonth == 1 && dayOfWeek <= 7 && dayOfWeek >= 2) month -= 1;
                addCourse_Index(week_view, d, 0, month + "\n月", Color.parseColor("#80ffffff"));
            } else//Day of week index
            {
                if (dayOfWeek == i)//当前日期
                {
                    if (dayOfMonth == 1 && dayOfWeek <= 7 && dayOfWeek >= 2) {
                        addCourse_Index(week_view, 2 * d, 0, (getMonth() + 1) + "月\n" + numberToWeekDay(i), Color.parseColor("#800000ff"));
                    } else
                        addCourse_Index(week_view, 2 * d, 0, dayOfMonth + "\n" + numberToWeekDay(i), Color.parseColor("#800000ff"));
                } else {
                    int fbDayOfMonth = dayOfMonth - (dayOfWeek - i);//前后日期
                    if (fbDayOfMonth == 1) {
                        addCourse_Index(week_view, 2 * d, 0, (getMonth() + 1) + "月\n" + numberToWeekDay(i), Color.parseColor("#80ffffff"));
                        continue;
                    }
                    if (fbDayOfMonth > getDaysOfMonth(-1)) {
                        fbDayOfMonth -= getDaysOfMonth(0);
                    }
                    if (fbDayOfMonth <= 0) {
                        fbDayOfMonth = getDaysOfMonth(-1) + fbDayOfMonth;
                    }
                    addCourse_Index(week_view, 2 * d, 0, fbDayOfMonth + "\n" + numberToWeekDay(i), Color.parseColor("#80ffffff"));
                }
            }
        }
        return week_view;
    }

    private int getDaysOfMonth(int offSetToMonthNow) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        calendar.add(Calendar.MONTH, offSetToMonthNow);
        int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        return days;
    }

    private int getYear() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        int year = calendar.get(Calendar.YEAR);
        //月份从0开始第几...
        return year;
    }

    private int getMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        int month = calendar.get(Calendar.MONTH);
        //月份从0开始第几...
        return month + 1;
    }

    private int getDayOfMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        int dayOfMonth = calendar.get(Calendar.DATE);
        return dayOfMonth;
    }

    private int getDayOfWeek() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        Log.i("", "dayOfWeek" + dayOfWeek);
        //星期从星期天开始第几...
        return --dayOfWeek == 0 ? 7 : dayOfWeek;
    }

    private void addCourse_Index(ViewGroup viewGroup, int width, int height, String text, int color) {
        Course_Index course_Index = new Course_Index(getActivity(), text);
        course_Index.setBackgroundColor(color);

        LayoutParams layoutParams = new LayoutParams();
        layoutParams.width = width;
        layoutParams.setMargins(1, 1, 1, 1);
        if (height != 0) {
            layoutParams.height = height;
        }
        viewGroup.addView(course_Index, layoutParams);
    }

    private void addCourse_Card(ViewGroup viewGroup, int width, int height, String text, int row, int col, int color) {
        Course_Card course_Card = new Course_Card(getActivity(), text);
        //course_Card.setBackgroundResource(R.drawable.course_card_shape);
        course_Card.setCourseColor(color);
        FrameLayout cardContainer = new FrameLayout(getActivity());
        cardContainer.addView(course_Card);

        LayoutParams layoutParams = new LayoutParams();
        layoutParams.setMargins(1, 1, 1, 1);
        layoutParams.width = width;
        layoutParams.height = height;
        layoutParams.rowSpec = GridLayout.spec(row, height / (2 * d));
        layoutParams.columnSpec = GridLayout.spec(col);

        viewGroup.addView(cardContainer, layoutParams);
    }

    private String numberToWeekDay(int num) {
        String weekday = null;
        switch (num) {
            case 1:
                weekday = "周一";
                break;
            case 2:
                weekday = "周二";
                break;
            case 3:
                weekday = "周三";
                break;
            case 4:
                weekday = "周四";
                break;
            case 5:
                weekday = "周五";
                break;
            case 6:
                weekday = "周六";
                break;
            case 7:
                weekday = "周日";
                break;
            default:
                break;
        }
        return weekday;
    }

    protected void showCourseMenuDropdown() {
        PopupMenu popupMenu = new PopupMenu(getActivity(), actionbar_menu);
        popupMenu.inflate(R.menu.course_popupmenu);

		/*
         * 利用反射强制开启PopupMenu的icon显示
		 * http://stackoverflow.com/questions/20836385/popup-menu-with-icon-on-android
		 */
        try {
            Field field = popupMenu.getClass().getDeclaredField("mPopup");
            field.setAccessible(true);
            Object menuPopupHelper = field.get(popupMenu);
            Method method = menuPopupHelper.getClass().getDeclaredMethod("setForceShowIcon", Boolean.TYPE);
            method.setAccessible(true);
            method.invoke(menuPopupHelper, true);
        } catch (Exception e) {
            e.printStackTrace();
        }

        popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.course_menu_import:
                        GetNetCourseDataView();
                        break;
                    case R.id.course_menu_setterm:
                        showCourseTermsetDialog();
                        break;
                    case R.id.course_menu_setaccount:
                        showCourseLoginDialog();
                        break;
                }
                return false;
            }
        });

        popupMenu.show();
    }

    protected void showCourseTermsetDialog() {
        Dialog dialog = new Dialog(getActivity()) {
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.course_select_term_dialog);

                final NumberPicker year = (NumberPicker) findViewById(R.id.npYear);
                year.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
                year.setMinValue(2007);
                year.setMaxValue(getYear());
                year.setFormatter(new NumberPicker.Formatter() {
                    @Override
                    public String format(int value) {
                        return value + "-" + (value + 1);
                    }
                });

                final NumberPicker term = (NumberPicker) findViewById(R.id.npTerm);
                term.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
                term.setMinValue(1);
                term.setMaxValue(2);
                term.setFormatter(new NumberPicker.Formatter() {
                    @Override
                    public String format(int value) {
                        return "第" + value + "学期";
                    }
                });

                Button btnCancle = (Button) findViewById(R.id.btnCancle);
                btnCancle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                    }
                });

                Button btnOK = (Button) findViewById(R.id.btnOK);
                btnOK.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int y = year.getValue();
                        SchoolUtil.xnd = y + "-" + (y + 1);
                        SchoolUtil.xqd = term.getValue() + "";

                        SharedPreferences loginPreferences = getActivity().getApplicationContext().getSharedPreferences("QueryCourseSetting", Context.MODE_PRIVATE);
                        Editor editor = loginPreferences.edit();
                        editor.putString("xnd", SchoolUtil.xnd);
                        editor.putString("xqd", SchoolUtil.xqd);
                        editor.commit();

                        GetLocalCourseDataView();
                        dismiss();
                    }
                });

            }
        };
        dialog.setCancelable(false);
        dialog.setTitle("选择学年和学期");
        dialog.show();
    }

    protected void showCourseLoginDialog() {
        Dialog dialog = new Dialog(getActivity()) {
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.course_login_dialog);

                Button btnLogin = (Button) findViewById(R.id.btnLogin);
                btnLogin.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String username = ((EditText) findViewById(R.id.etUsername)).getText().toString();
                        String password = ((EditText) findViewById(R.id.etPassword)).getText().toString();
                        if (username.equals("") || password.equals("")) {
                            Toast.makeText(getActivity(), "请输入学号和密码", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        SchoolUtil.course_username = username;
                        SchoolUtil.course_password = password;

                        SharedPreferences courseLocalSharedPreferences = getActivity().getApplicationContext().getSharedPreferences("CourseDataLocal", Context.MODE_PRIVATE);
                        courseLocalSharedPreferences.edit().clear().commit();
                        SharedPreferences loginPreferences = getActivity().getApplicationContext().getSharedPreferences("LoginToSchool", Context.MODE_PRIVATE);
                        loginPreferences.edit().clear().commit();

                        GetNetCourseDataView();
                        dismiss();
                    }
                });

                Button btnCancle = (Button) findViewById(R.id.btnCancle);
                btnCancle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                        Toast.makeText(getActivity(), "请输入学号和密码", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        };
        dialog.setTitle("登陆教务处");
        dialog.setCancelable(false);
        dialog.show();
    }

    protected void showCourseWeekDropdown() {
        ArrayList<Map<String, String>> weeks = new ArrayList<Map<String, String>>();
        for (int i = 1; i <= 25; i++) {
            Map<String, String> weekMap = new HashMap<String, String>();
            if (i == nowWeek) {
                weekMap.put("weekName", "第" + i + "周(本周)");
            } else {
                weekMap.put("weekName", "第" + i + "周");
            }
            weeks.add(weekMap);
        }

        LinearLayout course_week_dropdown_popwindow = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.course_week_dropdown_popwindow, null);
        ListView course_week_dropdown_ListView = (ListView) course_week_dropdown_popwindow.findViewById(R.id.course_week_dropdown_ListView);

        final PopupWindow popupWindow = new PopupWindow(course_week_dropdown_popwindow);
        popupWindow.setFocusable(true);

        course_week_dropdown_ListView.setAdapter(
                new SimpleAdapter(
                        getActivity(),
                        weeks,
                        R.layout.course_week_dropdown_popitem,
                        new String[]{"weekName"},
                        new int[]{R.id.course_week_dropdown_tv}) {
                    public View getView(int position, View convertView, ViewGroup parent) {
                        View view = super.getView(position, convertView, parent);

                        TextView weekItemTV = (TextView) view.findViewById(R.id.course_week_dropdown_tv);

                        weekItemTV.setHeight(2 * d);

                        if (getItemId(position) + 1 == nowWeek) {
                            weekItemTV.setTextColor(Color.WHITE);
                            weekItemTV.setBackgroundColor(Color.parseColor("#98de82"));
                        } else {
                            weekItemTV.setTextColor(Color.parseColor("#0997F7"));
                            weekItemTV.setBackgroundColor(Color.TRANSPARENT);
                        }

                        return view;
                    }

                    ;
                }
        );

        course_week_dropdown_ListView.setOnItemClickListener(
                new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        TextView weekItemTV = null;
                        if (id + 1 == selectedWeek) {
                            return;
                        }
                        if (selectedWeek != 0 && id != selectedWeek - 1) {
                            int itemsInView = parent.getChildCount();
                            for (int i = 0; i < itemsInView; i++) {
                                View view2 = parent.getChildAt(i);
                                weekItemTV = (TextView) view2.findViewById(R.id.course_week_dropdown_tv);

                                Pattern pattern = Pattern.compile("[^非]本周");
                                Matcher matcher = pattern.matcher(weekItemTV.getText().toString());
                                if (!matcher.find()) {
                                    weekItemTV.setTextColor(Color.parseColor("#0997F7"));
                                    weekItemTV.setBackgroundColor(Color.TRANSPARENT);
                                }
                            }

                            if (id + 1 == nowWeek) {
                                selectedWeek = nowWeek;
                                week_dropdown.setText("第" + nowWeek + "周");
                                GetLocalCourseDataView();
                                return;
                            }
                        }
                        weekItemTV = (TextView) view.findViewById(R.id.course_week_dropdown_tv);
                        weekItemTV.setTextColor(Color.WHITE);
                        weekItemTV.setBackgroundColor(Color.parseColor("#f2dc9c"));
                        week_dropdown.setText(weekItemTV.getText().toString() + "(非本周)");
                        selectedWeek = id + 1;
                        GetLocalCourseDataView();
                    }
                }
        );

        course_week_dropdown_ListView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        popupWindow.setWidth(course_week_dropdown_ListView.getMeasuredWidth());
        int visibleWeeks = 5;
        popupWindow.setHeight(course_week_dropdown_ListView.getMeasuredHeight() * (visibleWeeks + 1));

        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.mipmap.ic_dropdown_week_bg));
        popupWindow.setOutsideTouchable(true);
		
		/*
		 * showAsDropDown(anchor); 以触发弹出窗的view为基准，出现在view的正下方，弹出的pop_view左上角正对view的左下角  偏移量默认为0,0showAsDropDown(anchor, xoff, yoff); 有参数的话，就是一view的左下角进行偏移，xoff正的向左，负的向右. yoff没测，也应该是正的向下，负的向上showAtLocation(parent, gravity, x, y); 
		 * parent:传你当前Layout的id;  
		 * gravity:Gravity.BOTTOM（以屏幕左下角为参照）... 偏移量会以它为基准点 当x y为0,0是出现在底部居中 
		 */
        int xOffset = (week_dropdown.getWidth() - course_week_dropdown_ListView.getMeasuredWidth()) / 2;
        popupWindow.showAsDropDown(week_dropdown, xOffset, 0);

        Button btnSetWeek = (Button) course_week_dropdown_popwindow.findViewById(R.id.course_week_dropdown_btnSetWeek);
        btnSetWeek.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                nowWeek = (int) selectedWeek;
                SharedPreferences nowWeekSharedPreferences = getActivity().getApplicationContext().getSharedPreferences("nowWeek", Context.MODE_PRIVATE);
                nowWeekSharedPreferences.edit().putInt("nowWeek", nowWeek).commit();
                week_dropdown.setText("第" + nowWeek + "周");
                popupWindow.dismiss();
                Toast.makeText(getActivity(), "第" + nowWeek + "周为当前周", Toast.LENGTH_SHORT).show();
            }
        });
    }

}
